<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\helpers\v1\traits\FileUpload;
use app\api\model\v1\Admins;
use app\api\model\v1\Comments;
use app\api\model\v1\EnterUnit;
use app\api\model\v1\Facts;
use app\api\model\v1\FactScore;
use app\api\model\v1\FactsOut;
use app\api\model\v1\OnlineUnitDetail;
use app\api\model\v1\Reply;
use app\api\model\v1\SystemConfig;
use app\api\model\v1\Users;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Env;
use think\Request;

class FactSystem extends BaseController
{
    use FileUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 14:44
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 爆料列表
     */
    public function getFactList()
    {
        $limit = $this->request->param('limit', 10);
        $map = [];
        if ($this->request->has('fact_type') && !empty($this->request->param('fact_type'))) {
            if($this->request->param('fact_type')==1){
                $map[] = ['fact_type', 'IN', [1,5]];
            }else{
                $map[] = ['fact_type', '=', $this->request->param('fact_type')];
            }

        }

        if ($this->request->has('is_finish') && is_numeric($this->request->param('is_finish'))) {
            $map[] = ['is_finish', '=', $this->request->param('is_finish')];
        }
        if ($this->request->has('user_id') && is_numeric($this->request->param('user_id'))) {
            $map[] = ['user_id', '=', $this->request->param('user_id')];
        }
        if ($this->request->has('unit_id') && is_numeric($this->request->param('unit_id'))) {
            $map[] = ['unit_id', '=', $this->request->param('unit_id')];
        }
        $type = $this->request->param('type', 2);
        if (intval($type) === 1) {
            $admin = Admins::find($this->request->uid);
            if ($admin['enter_unit_id'] !== 0) {
                $map[] = ['unit_id', '=', $admin['enter_unit_id']];
            }
        }
        $date = date("Y-m-d");
        $res = Facts::with(['unit', 'score'])->where($map)->withCount(['replyCount'])->order('id desc')->paginate($limit)->each(function ($item, $key)use($date) {
            if ($item['way_id'] !== 0) {
                $item['way_name'] = Facts::$fact_way[$item['way_id']] ?? '直播录入';
            }else{
                $item['way_name'] = '直播录入或其他';
            }
            $item['createTime'] = date("Y-m-d",strtotime($item['create_time']));
            $item['fact_type_name'] = Facts::$fact_type[$item['fact_type']];
            $isyq=0;
            if(!$item['reply_date']){
                if($date >=$item['plan_date']){
                    $isyq=1;
                }
            }
            $item['isyq']=$isyq;
            return $item;
        });
        return $this->response($res);
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 16:07
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取唯一信息
     */
    public function getFactShowInfo()
    {
        $id = $this->request->param('id', 0);
        $res = Facts::with(['unit', 'replyCount', 'score', 'user', 'comment' => ['reply' => function($q){
            $q->with(['user'=>['unit'=>function($query){
                $query->field('id,title');
            }]])->order('id desc');
            return $q;
        }], 'user'])->find($id);
        if (is_null($res)) {
            return $this->response(403, "暂未找到该信息");
        }
        if ($res['way_id'] !== 0) {
            $res['way_name'] = Facts::$fact_way[$res['way_id']];
            $res_img = json_decode($res['accessory_path'], true);
            $res['new_path'] = $res_img;
        }
        $res['name'] = $res['user']['nickname']; //此为头像
        $res['url'] = $res['user']['head_img']; //此为头像
        $res['fact_type_name'] = Facts::$fact_type[$res['fact_type']];
        $res['allReply'] = (count($res['replyCount']) + count($res['comment'])) ?? 0;
        $res['unit_title'] = $res['unit']['title'] ?? '';
        $res['createTime'] = date("Y-m-d",strtotime($res['create_time']));
        foreach ($res['comment'] as $key => $v) {
            $v['name'] = $v['user']['nickname'] ?? '';
            $v['url'] = $v['user']['head_img'] ?? ''; //此为头像
            $v['createTime'] = date("Y-m-d",strtotime($v['create_time']));
            $reply = $v['reply'];
            if (!empty($reply)) {
                foreach ($reply as $k1=>$v1){
                    $reply[$k1]['name'] = $reply['user']['nickname'] ?? '';
                    $reply[$k1]['createTime'] = date("Y-m-d",strtotime($v1['create_time']));
                    if (!empty($v1['user']['unit'])){
                        $reply[$k1]['unit_name'] = $v1['user']['unit']['title'] ?? '';
                    }
                    if ($v1['is_attachment'] === 2){
                        $res_img = json_decode(    $v1['img_path'], true);
                        $reply[$k1]['new_img_path'] = $res_img;
                    }
                }


//                $reply['url'] =  $reply['user']['head_img']; //此为头像
            }
        }
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 9:00
     * @return \think\response\Json
     * 获取爆料类型
     */
    public function factType()
    {
        $res = Facts::$fact_type;
        $new_arr = [];
        foreach ($res as $key => $v) {
            $new_arr[$key]['id'] = $key;
            $new_arr[$key]['title'] = $v;
        }
        return $this->response(array_values($new_arr));
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 9:12
     * @return \think\response\Json
     * 获取诉求方式
     */
    public function factWay()
    {
        $res = Facts::$fact_way;
        $new_arr = [];
        foreach ($res as $key => $v) {
            $new_arr[$key]['id'] = $key;
            $new_arr[$key]['title'] = $v;
        }
        return $this->response(array_values($new_arr));
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 14:36
     * 保存
     * 2023-7-9 加入计划日期
     */
    public function saveFact()
    {

        $data = $this->request->param();

        //过滤
        $data['filter_content'] = $this->filterSensitive($data['content']);
        if (!empty($data['way_id'])) {
            $data['accessory_path'] = json_encode($data['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
            $data['is_exist'] = Facts::IS_EXIST_ONE;
        }
        $data['user_id'] = $this->request->wx_user_id ?? 0; //需要更改

        $uer = Users::find($data['user_id']);
        if (is_null($uer)){
            return $this->response(400,'当前用户不存在请重新登录！');
        } else if (is_null($uer['mobile'])){
            return $this->response(400,'系统未检测出您的手机号,请重新登录！');
        }else{

            //获取计划日期
            $plan_date = Facts::doPlan();
            $data['plan_date']=$plan_date;

            //添加到评论表中
            $res_id = Facts::create($data)->id;
            if ($res_id > 0) {
                Comments::create([
                    'fact_id' => $res_id,
                    'user_id' => $this->request->wx_user_id ?? 0,
                    'comment_content' => $data['content'],
                    'filter_comment_content' => $data['filter_content']
                ]);
            }
            $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>$data['unit_id'],'is_notice'=>1])->find();
            if (!is_null($admin)){
                //手机号
                $mobile = $admin['mobile'];
                $user = Users::find($this->request->wx_user_id);
                $handsetTailNumber = mb_substr($user['mobile'],7,11) ?? '0000'; //手机尾号
                $fact_type= Facts::$fact_type[$data['fact_type']] ?? '其他';
                //短信回复
                Message::sendMessage($mobile,$handsetTailNumber,2,$fact_type,$res_id);
            }
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 16:47
     * 主持人直播的时候现场从系统录入的
     * 2023-7-9 加入计划日期
     */
    public function batchSaveFact()
    {
        $data = $this->request->param();

        if ($data['user_id'] === 0 && $data['mobile'] !== "") {
            $user_id = Users::create([
                'nickname' => $data['contact'] ?? '随机',
                'mobile' => $data['mobile'],
                'is_management' => Users::IS_MANAGEMENT_ZERO,
                'is_auth' => Users::IS_AUTH_THREE,
                'head_img' => Env::get('HTTP.http', 'HTTP.default_http') . 'storage/static/image/zanwu.jpg'
            ])->id;
        } else {
            $user_id = $data['user_id'];
        }
        if ($data['mobile'] !== ""){
            $source = '直播时PC录入';
        }else{
            $source = '直播时PC录入/没写手机号';
        }
        $question_arr = $data['question'];
        $new_arr = [];
        foreach ($question_arr as $key => $value) {
            $content = $value['content'] ?? $value['title'];
            $new_arr['unit_id'] = $data['unit_id'];
            $new_arr['fact_type'] = $data['fact_type'];
            $new_arr['address'] = $data['address'];
            $new_arr['title'] = $value['title'];
            $new_arr['content'] = $content;
            $new_arr['filter_content'] = $this->filterSensitive($content);
            $new_arr['user_id'] = $user_id;
            $new_arr['source'] = $source;


            //获取计划日期-并加计划日期加入爆料表
            $plan_date = Facts::doPlan();
            $new_arr['plan_date']=$plan_date;

            //添加到评论表中
            $res_id = Facts::create($new_arr)->id;
            if ($res_id > 0) {
                Comments::create([
                    'fact_id' => $res_id,
                    'user_id' => $user_id,
                    'comment_content' => $content,
                    'filter_comment_content' => $this->filterSensitive($content)
                ]);
            }
        }
        $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>$data['unit_id'],'is_notice'=>1])->find();
        if (!is_null($admin)){
            //手机号
            $mobile = $admin['mobile'];
            $user = Users::find($user_id);
            if(empty($user)){
                $handsetTailNumber = '0000';
            }else{
                $handsetTailNumber = mb_substr($user['mobile'],7,11) ?? '0000'; //手机尾号
            }
//            $handsetTailNumber = mb_substr($user['mobile'],7,11) ?? '0000'; //手机尾号
            $fact_type= Facts::$fact_type[$data['fact_type']] ?? '其他';
            //短信回复
            Message::sendMessage($mobile,$handsetTailNumber,2,$fact_type);
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 17:15
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 监测手机号
     */
    public function checkUserMobile()
    {
        $data = $this->request->param();
        $user = Users::where(['mobile' => $data['mobile']])->find();
        if (is_null($user)) {
            return $this->response(403, '系统中暂未找到该用户');
        }
        return $this->response($user->toArray());
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 13:54
     * @return \think\response\Json
     * 上传照片
     */
    public function uploadFactImg()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->save($file, 'fact_img');
        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/5
     * @Time: 12:59
     * @return \think\response\Json
     * 上传预案 暂未封装
     */
    public function uploadPlan()
    {
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $upload_type = $this->request->param('upload_type', 'doc,xls,ppt,pdf,docx,xlsx,pptx');
        try {
            validate(['file' => [
                'fileSize' => 1024 * 1024 * 5,
                'fileExt' => $upload_type
            ]])->check(['file' => $file]);
            $saveName = \think\facade\Filesystem::disk('public')
                ->putFile('program_plan', $file);
            $path = str_replace('\\', '/', $saveName);
            return $this->response(['path' => $path, 'state' => true]);

        } catch (ValidateException $e) {
            return $this->response(403, '只能上传pdf,doc,xlsx,xls,ppt格式的文件');
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 17:55
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存继续发布言论
     */
    public function saveComment()
    {
        $data = $this->request->param();
        $data['filter_comment_content'] = $this->filterSensitive($data['comment_content']);
        $data['user_id'] = $this->request->wx_user_id ?? 0; //当前发布人的id
        Comments::create($data);
        $fact = Facts::find($data['fact_id']);
        if (!is_null($fact)){
            $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>$fact['unit_id'],'is_notice'=>1])->find();
            if (!is_null($admin)){
                //手机号
                $mobile = $admin['mobile'];
                $user = Users::find($this->request->wx_user_id);
                $handsetTailNumber = mb_substr($user['mobile'],7,11) ?? '0000'; //手机尾号
                $fact_type= Facts::$fact_type[$fact['fact_type']] ?? '其他';
                //短信回复
                Message::sendMessage($mobile,$handsetTailNumber,2,$fact_type);
            }
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/2
     * @Time: 18:06
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 打分
     */
    public function saveScoreAndOver()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->request->wx_user_id ?? 0; //当前发布人的id
        $fact_id = intval($data['fact_id']);
        $fact = Facts::find($fact_id);
        if (is_null($fact)) {
            return $this->response(501, '暂未找到该资源,请联系管理员');
        }
        $is_true = $fact->save([
            'is_finish' => Facts::IS_FINISH_ONE //更新状态已完成打分功能
        ]);
        if (!$is_true) {
            return $this->response(501, '打分写入失败,请联系管理员');
        }
        FactScore::create($data);
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/5
     * @Time: 11:09
     * 回复评论
     * 2023-7-9 增加回复时间，修改计划状态
     */
    public function replyToComment()
    {
        $data = $this->request->param();

        $source = $this->request->param('source', 'wx');
        $data['filter_reply_content'] = $this->filterSensitive($data['reply_content']);
        if ($source === 'pc') {
            $user = Users::where(['admin_id' => $this->request->uid])->find();
            if (is_null($user)) {
                $reply_user_id = 0;
            } else {
                $reply_user_id = $user->id ?? 0;
            }
            $data['reply_user_id'] = $reply_user_id; //当前回复的id
        } else {
            $data['reply_user_id'] = $this->request->wx_user_id ?? 0; //当前回复的id
        }
        if (!empty($data['img_path'])) {
            $data['img_path'] = json_encode($data['img_path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
            $data['is_attachment'] = 2; //存在
        }
        Reply::create($data);

        //修改回复时间，修改计划状态
        $reply_date=date("Y-m-d H:i:s");
        Facts::doReply($data['fact_id'],$reply_date);

        $user = Users::find($data['reply_to_user_id']);
        if (!is_null($user)){
            $fact = Facts::find($data['fact_id']);
            $unit = EnterUnit::find($fact['unit_id']);
            $mobile = $user['mobile']; //回复的手机号
            Message::sendMessage($mobile,'',1,$unit['title'] ?? '系统单位');
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/5 16:46
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * /案件退回
     */
    public function outFact()
    {
        $data = $this->request->param();
        $fact = Facts::withCount(['replyCount'])->find($data['fact_id']);
        if (is_null($fact)) {
            return $this->response(403, '暂未找到该案件');
        }
        if ($fact['reply_count_count'] > 0) {
            return $this->response(403, '该案件您已经参与回复了,无法退回');
        }
        $fact->save(['is_out' => Facts::IS_OUT_ONE]); //更新状态
        $out_data = [
            'fact_id' => $data['fact_id'],
            'user_id' => $this->request->wx_user_id,
            'out_content' => $data['out_content'],
            'out_unit_id' => $fact['unit_id'],
            'out_status' => FactsOut::OUT_ZERO
        ];
        FactsOut::create($out_data);
        $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>0,'is_notice'=>1])->find();
        if (!is_null($admin)){
            $mobile = $admin['mobile'];
            $fact = Facts::with(['unit'])->find($data['fact_id']);
            Message::sendMessage($mobile,'',3,$fact['unit']['title'] ?? '系统单位');
        }
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/5
     * @Time: 17:01
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取退回列表
     */
    public function getOutFactList()
    {
        $limit = $this->request->param('limit', 10);
        $out_status = $this->request->param("status",'0',"intval");

        $map=[];
        $map[] = array('out_status', '=', $out_status);
//        $map[] = array('out_status', '=', FactsOut::OUT_ZERO);
        $res = FactsOut::with(['facts', 'unit'])->where($map)->paginate($limit)->each(function ($item, $key) {
            if (!is_null($item['facts'])){
                if ($item['facts']['way_id'] !== 0) {
                    $item['way_name'] = Facts::$fact_way[$item['facts']['way_id']];
                }else{
                    $item['way_name'] = '';
                }
                $item['fact_type_name'] = Facts::$fact_type[$item['facts']['fact_type']];
            }else{
                $item['way_name'] = '';
                $item['fact_type_name'] = '未知';
            }


            return $item;
        });;
        return $this->response($res);
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/9/5
     * @Time: 17:50
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同意退回
     */
    public function agreeOutFact()
    {
        $data = $this->request->param();
        $out = FactsOut::find($data['out_id']);
        if (is_null($out)) {
            return $this->response(403, '暂未找到该退回记录');
        }
        $fact = Facts::find($data['fact_id']);
        if (is_null($fact)) {
            return $this->response(403, '暂未找到该案件');
        }
        $unit = EnterUnit::find($data['unit_id']);
        if (is_null($unit)) {
            return $this->response(403, '该单位不存在');
        }
        $day = date("Y-m-d");
        $plan_date = (new OnlineUnitDetail())->doNextday($day);
        $fact->save([
            'is_out' => FactsOut::OUT_THREE,
            'unit_id' => $data['unit_id'],
            'plan_date' =>$plan_date
        ]); //同意
        //更新原始表记录
        $out->save(['out_status' => FactsOut::OUT_ONE]);  //同意
        //新增记录表
        $operation_id = $this->request->wx_user_id;
        if(!$operation_id){
            $operation_id =  $data['wx_user_id'];
        }
        $new_out_data = [
            'fact_id' => $data['fact_id'],
            'operation_id' => $operation_id,
            'user_id' => $out->user_id,
            'out_status' => FactsOut::OUT_THREE,
            'out_unit_id' => $data['unit_id']
        ];
        FactsOut::create($new_out_data);
        $fact = Facts::find($data['fact_id']);
        if (!is_null($fact)){
            $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>$fact['unit_id'],'is_notice'=>1])->find(); //通知退回人
            $admin2 = Admins::field('id,mobile')->where(['enter_unit_id'=>$data['unit_id'],'is_notice'=>1])->find(); //最新接收单位
            if (!is_null($admin2)){ //通知接收人
                //手机号
                $mobile = $admin2['mobile'];
                //短信回复
                Message::sendMessage($mobile,'',4,'');
            }
//            if (!is_null($admin)){ //通知退回人
//                //手机号
//                $mobile = $admin['mobile'];
//                //短信回复
//                Message::sendMessage($mobile,'',5,'同意'); //通知退回人
//            }
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/6
     * @Time: 8:54
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 拒绝
     */
    public function refuseOutFact()
    {
        $data = $this->request->param();
        $out = FactsOut::find($data['out_id']);
        if (is_null($out)) {
            return $this->response(403, '暂未找到该退回记录');
        }
        $fact = Facts::find($data['fact_id']);
        if (is_null($fact)) {
            return $this->response(403, '暂未找到该案件');
        }
        $fact->save(['is_out' => Facts::IS_OUT_THREE]); //同意
        //更新原始表记录
        $out->save(['out_status' => FactsOut::OUT_TWO]);  //同意
        //新增记录表
        $new_out_data = [
            'fact_id' => $data['fact_id'],
            'operation_id' => $this->request->wx_user_id,
            'user_id' => $out->user_id,
            'out_status' => FactsOut::OUT_TWO,
            'refuse_content' => $data['refuse_content'],
            'out_unit_id' => $fact['unit_id']
        ];
        FactsOut::create($new_out_data);
        if (!is_null($fact)){
            $admin = Admins::field('id,mobile')->where(['enter_unit_id'=>$fact['unit_id'],'is_notice'=>1])->find(); //通知退回人
            if (!is_null($admin)){
                //手机号
                $mobile = $admin['mobile'];
                //短信回复
                Message::sendMessage($mobile,'',5,'拒绝'); //通知退回人
            }
        }
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/7
     * @Time: 17:54
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取案件的时间线
     */
    public function getTimeFactLine()
    {
        $fact_id = $this->request->param('id', 0);
        $res = Facts::with(['out' => ['unit']])->find($fact_id);
        if (is_null($res)) {
            return $this->response(403, '暂未找到该案件');
        }
        foreach ($res['out'] as $key => $va) {
            $va['out_type_name'] = FactsOut::$fact_is_out[$va['out_status']] ?? '';
        }

        return $this->response($res->toArray());
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/8
     * @Time: 16:20
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除 关联式删除评论和回复
     */
    public function deleteFact($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $res = Facts::with(['comment', 'replyCount'])->find($id);
            if (is_null($res)) {
                return $this->response(404, '未找到该数据');
            }
            $res->together(['comment', 'replyCount'])->force()->delete();
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 10:28
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 隐藏还是显示
     */
    public function isShowFact($id)
    {
        $res = Facts::find($id);
        if (is_null($res)) {
            return $this->response(404, '未找到该数据');
        }
        if ($res['is_show'] === Facts::IS_SHOW_ONE) {
            $is_show = Facts::IS_SHOW_TWO;
        } else if ($res['is_show'] === Facts::IS_SHOW_TWO) {
            $is_show = Facts::IS_SHOW_ONE;
        } else {
            $is_show = 0; //未知
        }
        $res->save([
            'is_show' => $is_show
        ]);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 10:37
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 是否强制关闭(关闭后无法回复及发表)
     */
    public function isCloseFact($id)
    {
        $res = Facts::find($id);
        if (is_null($res)) {
            return $this->response(404, '未找到该数据');
        }
        if ($res['is_close'] === Facts::IS_CLOSE_ONE) {
            $is_close = Facts::IS_CLOSE_TWO;
        } else if ($res['is_close'] === Facts::IS_CLOSE_TWO) {
            $is_close = Facts::IS_CLOSE_ONE;
        } else {
            $is_close = 0; //未知
        }
        $res->save([
            'is_close' => $is_close
        ]);
        return $this->response();
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/18
     * @Time: 18:19
     * @return \think\response\Json
     * 读取是否隐藏类别
     */
    public function IsHiddenType()
    {
        $res = Facts::$is_hidden;
        $new_arr = [];
        foreach ($res as $key => $v) {
            $new_arr[$key]['id'] = $key;
            $new_arr[$key]['title'] = $v;
            $new_arr[$key]['disabled'] = false;

        }
        return $this->response(array_values($new_arr));
    }



    public function SystemTest(){
        $mobile = '18956460683';
        $fact_type= '咨询';
        //短信回复
        Message::sendMessage($mobile,'6928',2,$fact_type);
        halt("成功");
    }

    public function tongji(){
        $qty_unit =  Facts::count("DISTINCT unit_id");
        $qty_user =  Facts::count("DISTINCT user_id");
        $qty_zb =  Facts::where("source='直播时PC录入'")->count();
        $qty_xx =  Facts::where("source='微信'")->count();
        $types = '交通法规、工资拖欠、小区管理';


        $date=date("m月d日");
        $day = date("Y-m-d");

        $num_gzr = 7;
        $dayModel = OnlineUnitDetail::where("online_status","<",3)
            ->where("online_date","<",$day)
            ->order("online_date DESC")
            ->limit(0,$num_gzr)
            ->select()
            ->toArray();
        $dayArr = end($dayModel);
        $dayPre = $dayArr['online_date'];
        $gzrRes = Facts::where("create_time",">",$dayPre)->select()->toArray();
        $gzr_qty = count($gzrRes);
        $gzr_wc = $gzr_wwc = 0;
        $unit_wc=$unit_wwc=[];
        foreach ($gzrRes as $key=>$vf){
            if($vf['reply_date']){
                $gzr_wc++;
                $unit_wc[]=$vf['unit_id'];
            }else{
                $gzr_wwc++;
                $unit_wwc[]=$vf['unit_id'];
            }
        }
        $str_wc = $str_wwc = '';
        if($gzr_wc){
            $units = EnterUnit::whereIn("id",$unit_wc)->select()->toArray();
            $units_name = implode(",",array_column($units,"title"));
            $str_wc="{$units_name}已在{$num_gzr}个工作日内将群众反映的{$gzr_qty}个问题的调查处理结果向政风行风热线进行了反馈，";
        }
        if($gzr_wwc){
            $units = EnterUnit::whereIn("id",$unit_wwc)->select()->toArray();
            $units_name = implode(",",array_column($units,"title"));
            $str_wc="{$units_name}已在{$num_gzr}个工作日内将群众反映的{$gzr_qty}个问题的调查处理结果向政风行风热线进行了反馈，同时向投诉咨询人进行了回复。";
            $str_wwc="听众反映的剩余{$gzr_wwc}个问题{$units_name}正在调查处理当中。";
        }

        $content = "{$qty_unit}家单位上线共接听{$qty_user}位听众打来的热线电话，群众反映的问题涉及{$types}等多个方面，现场答复{$qty_zb}条，交相关部门下线后调查处理{$qty_xx}条。";
        $content .= "截至{$date}{$str_wc}{$str_wwc}";
        return $this->response($content);
    }
}
